package cn.ecnu.controller.auth;

import cn.ecnu.common.Constant;
import cn.ecnu.common.utils.R;
import cn.ecnu.vo.auth.CaptchaLoginVo;
import cn.ecnu.vo.auth.RegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.ecnu.common.Constant.SMS_PREFIX;

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    // 使用手机号码-验证码登录
    @PostMapping("/loginWithPhone")
    public R loginWithPhoneAndCode(@RequestBody CaptchaLoginVo vo) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String code = ops.get(SMS_PREFIX + vo.getPhone()); // 获得对应号码的验证码
        if (StringUtils.equals(code, vo.getCode())) {
            // 验证码等相等, 登录成功
            // TODO: 登录成功后的操作, 比如授权token的操作
            return R.ok();
        }
        return R.error(Constant.CODE_ERROR, "验证码错误");
    }

    // 使用账号-密码登录 TODO

    // 使用手机号-验证码注册
    @PostMapping("/registerWithPhone")
    public R registerWithPhoneAndCode(@RequestBody RegisterVo vo) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String code = ops.get(SMS_PREFIX + vo.getPhone()); // 获得对应号码的验证码
        if (StringUtils.equals(code, vo.getCode())) {
            // 验证码等相等, 注册成功
            // TODO: 注册成功后的操作, 比如授权token的操作
            return R.ok();
        }
        return R.error(Constant.CODE_ERROR, "验证码错误"); //
    }


}
